//
//  ST_PecGroupListViewController.swift
//  btvideo
//
//  Created by mac on 2020/5/28.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import MJRefresh

/*组列表*/
class ST_PecGroupListViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


        title_nav_btn.setTitleForAllStates(self.title ?? "")
        
        
        self.view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+44, left: 0, bottom: 0, right: 0))
        }
        
        self.request_data()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(thumb_up_noti_handle(noti:)), name: Notification.Name.thumbUp, object: nil)
        
    }
    
    
    @objc fileprivate func thumb_up_noti_handle(noti:Notification){
        
        
//        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController,vc != self else{
            return
        }
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool else{
            return
        }
        
        guard let idx = data_array.firstIndex(where: {$0.group_id.string == id}) else{
            return
        }
            
        let index = Int(idx.uInt)
        
        data_array[safe: index]?.isThumbUp = isThumbUp
        
        if isThumbUp{
            data_array[safe: index]?.thumbUpCount += 1
        }else{
            data_array[safe: index]?.thumbUpCount -= 1
        }
        
        self.collectionView.performBatchUpdates({
            
            self.collectionView.reloadItems(at: [IndexPath.init(row: index, section: 0)])
            
        }) { (f) in
            
        }
            
    }
    
    var peculiarity_id = ""
    
    var groupId = 0
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        JVrequest(PH.fetchPeculiarityGroupListApi,parameters: ["page":currentPage,"feature_id":self.peculiarity_id,"group_id":self.groupId], success: { (json) in
            
            let list = json["data"].arrayValue
            
            let aArray = list.map { (itemJson) -> ST_TraitOfOperatCellModel in
                let m = ST_TraitOfOperatCellModel.init(json: itemJson)
                m.create_view_model_set(maxContentHeight: ST_ShowTraitCell.two_line_max_height)
//                喜欢的特质 所以 isAttention = true
                m.isAttention = true
                return m
            }
            
            
            if self.currentPage == 1{
                
                self.data_array = aArray
                
            }else{
                self.data_array += aArray
            }
            
            self.collectionView.mj_footer?.endRefreshing()
            self.pause_video()
            self.collectionView.reloadData {
                
                
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                
                self.play(indexPath: willPlayIdx)
                
              
                
                self.load_more_option_style(tableView: self.collectionView, count: list.count, pageSize: 20) {
                    
                    self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                        self?.request_data()
                    })
                }
            }
            
            print("当前返回数据:",json)
            
        }) { (code, err) in
            
            self.collectionView.mj_footer?.endRefreshing()
            
            self.toast(text: err)
        }
        
        
        
    }
    
//    MARK: - Properties
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
      let controlLayout = ST_CHTCollectionViewWaterfallLayout()
       controlLayout.minimumColumnSpacing = 15
       controlLayout.minimumInteritemSpacing = 15
       controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 10, bottom: 0, right: 10)
       return controlLayout
   }()
       
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: ST_TraitOfOperatCell.self)
        
//        control.register(cellWithClass: ST_PecGroupListOnlyImageCell.self)
        
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom, right: 0)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    //    MARK: SetUp Data
    fileprivate lazy var data_array = [ST_TraitOfOperatCellModel]()
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
    /**
     确定播放下一个indexPath
     */
    fileprivate func determined_will_play_index_path()->IndexPath?{
        
        var foundIndex:IndexPath?
        
//        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let currCell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(currCell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
//               大于 50% 还是展示自己
            if percent > 0.5{
                return curr
            }else{
                foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                    return item == currCell
                })
            }
        }else{
            
                // 取出第一个 video cell 播放
            foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                return false
            })
        }
        
        print("cell视频---切换到另外一个Item:",foundIndex?.item ?? "🈚️")
        
        return foundIndex
    }
    
    
    /**
     找出可以播放的indexPath
     */
    fileprivate func find_can_play_index_path(determineContinueBlock:((UICollectionViewCell)->(Bool)))->IndexPath?{
        
        var foundIndex:IndexPath?
        
        for item in collectionView.visibleCells {
            
            if determineContinueBlock(item){
                continue
            }
            
            var model:ST_PecGroupListCellModel?
         
            if let cell = item as? ST_PecGroupListCell{
                model = cell.model
            }
            
            
            if let item_model = model , item_model.type == 1{
                
                if let playIdx = collectionView.indexPath(for: item){

                 if let last = foundIndex,last.item < playIdx.item{
                     continue
                 }
                    
                let rectInScreen = collectionView.convert(item.frame, to: nil)
                            
                let intersect = containerRect.intersection(rectInScreen)
                
                let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
                //               小于 70% 换下一个哈
                if percent < 0.8{
                    continue
                }
                
               foundIndex = playIdx
                }
            }
        }
        
        return foundIndex
    }
    
    //    MARK:- Play Operation
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 20
        return control
    }()
    
    fileprivate lazy var transition = ST_PairsTransition()
    
    fileprivate var current_play_index_path:IndexPath?
     
    fileprivate func play(indexPath:IndexPath){
            
        pause_video()
        
        if TopmostViewController() != self{
            return
        }
        
        guard let cell = collectionView.cellForItem(at: indexPath) as? ST_PecGroupListCell , let dataItem = data_array[safe:indexPath.item] else{return}
        
        if dataItem.type != 1{
            
            return
        }
            
        cell.contentView.addSubview(playerView)
        
        let rect = cell.picutreframe_in_content_view()
         
        playerView.frame = rect
        
        let currModel = ST_PairsShareParticularModel.init(imageUrl: dataItem.imageUrl, videoUrl: dataItem.videoUrl, width: dataItem.width, height: dataItem.height)
        
        playerView.setUp(data_array: [currModel])
        
        current_play_index_path = indexPath
    }
    
    fileprivate func pause_video(){
        
        if playerView.frame.width == ScreenWidth{
            return
        }
        playerView.clear_data()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
        
        current_play_index_path = nil
    }
}

extension ST_PecGroupListViewController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let m = data_array[indexPath.row]
            
        
        return m.size
       
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let m = data_array[indexPath.item]
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_TraitOfOperatCell.self, for: indexPath)
        
        cell.max_content_number_of_lines = 2
        
        cell.model = m
        
        return cell
        
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        guard let currCell = collectionView.cellForItem(at: indexPath),let objCell = currCell as? ST_PecGroupshareViewRectProtocol else{
            return
        }
        
        let model = data_array[indexPath.row]

        //      当前正在播放 并且不是当前点击这个
        if current_play_index_path != indexPath{
            
            pause_video()
//            1视频 2 图片
            if model.type == 1{

                let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, videoUrl: model.videoUrl, width: model.width, height: model.height)
                
                playerView.setUp(data_array: [currModel])
            }else{
                
                let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, width: model.width, height: model.height)
                
                playerView.setUp(data_array: [currModel])
                
            }
            
        }
        
        transition.operationView = self.playerView
        
        let rectInScreen = currCell.convert(objCell.picutreframe_in_content_view(), to: nil)
        
        playerView.present_start_rect = rectInScreen
        playerView.present_start_idx = indexPath
        playerView.fromeController = self
     
        let size = CGSize.init(width: model.width, height: model.height)
        
        ST_InteractiveST_PeculiarityGroupViewController.present_interactive_peculiarity_group_controller(accid: model.accid, groupId: model.group_id.string, peculiarity_id: self.peculiarity_id, remark: model.sign, firstPhotoSize: size, transition: transition, presentRootController: self)
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
           
           //        判断当前正在播放的cell 在显示吗
           if let curr = current_play_index_path,let cell = collectionView.cellForItem(at: curr){
              
               let rectInScreen = collectionView.convert(cell.frame, to: nil)
               
               if containerRect.intersects(rectInScreen) == false{
                   pause_video()
               }
        }
        
    }
    
//    MARK: 停止滚动
   func scrollviewdidEndScroll(_ scrollView:UIScrollView){
       
       guard let willPlayIdx = determined_will_play_index_path() else {
           
           pause_video()
           
           return
       }
       
       if let curr = current_play_index_path,curr.item == willPlayIdx.item{
           return
       }
       
       play(indexPath: willPlayIdx)
       
   }
}


extension ST_PecGroupListViewController:ST_PairsTransitionProtocol{
    
    
    func present_start_cell()->UICollectionViewCell?{
        
        guard let idx = playerView.present_start_idx  else {
            return nil
        }
        
        return self.collectionView.cellForItem(at: idx)
        
    }
    
}







